<template>
  <!-- 发放记录表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1100px"
      draggable
      @close="closeDialog"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="单据号"
                prop="recordCode"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.recordCode"
                  placeholder="保存时自动生成"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.recordCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="原始凭证号"
                prop="originalVoucherNo"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly && !formData.originalVoucherNo"
                  v-model="formData.originalVoucherNo"
                  placeholder="请输入原始凭证号"
                  clearable
                  @focus="openApplySelectDialog()"
                />
                <el-input
                  v-if="!props.isReadonly && formData.originalVoucherNo"
                  v-model="formData.originalVoucherNo"
                  placeholder="请选择原始凭证号"
                  clearable
                  @focus="openApplySelectDialog()"
                >
                  <template #append>
                    <div class="cursor-pointer" @click="getInfo">
                      查看
                    </div></template
                  >
                </el-input>
                <el-link v-else type="primary" @click="getInfo">{{
                  formData.originalVoucherNo || ""
                }}</el-link>
                <!-- <span v-else class="">{{ formData.originalVoucherNo }}</span> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="发放日期"
                prop="grantDate"
                style="width: 100%"
              >
                <el-date-picker
                  style="width: 500px"
                  v-if="!props.isReadonly"
                  v-model="formData.grantDate"
                  type="date"
                  placeholder="请选择发放日期"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                />
                <span v-else>{{
                  dayjs(formData.grantDate).format("YYYY-MM-DD")
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="发放人"
                prop="grantPersonName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.grantPersonName"
                  placeholder="请输入发放人"
                  clearable
                  disabled
                />
                <span v-else>{{ formData.grantPersonName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="发放类型"
                prop="grantPersonType"
                style="width: 100%"
              >
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.grantPersonType"
                  clearable
                  style="width: 500px"
                  placeholder="请选择发放类型"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList('GrantType')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName(
                    "GrantType",
                    formData.grantPersonType
                  )
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="发放原因"
                prop="grantReason"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.grantReason"
                  placeholder="请输入发放原因"
                  clearable
                />
                <span v-else>{{ formData.grantReason }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="领用部门"
                prop="receiveDepartmentId"
                style="width: 100%"
              >
                <SelectOriganizationDangerGrant
                  v-if="!props.isReadonly"
                  @change="(ids:string) => getSelectIds(ids, '领用部门')"
                  @change-data="(datas) => getSelectDatas(datas, '领用部门')"
                  :isCheckStrictly="true"
                  :isMultiple="false"
                  :disabled="false"
                  :data="dataObject('领用部门')"
                  :selectData="formData.receiveDepartmentId"
                />
                <span v-else>{{ formData.receiveDepartmentName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="领用人"
                prop="receivePersonId"
                style="width: 100%"
              >
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.receivePersonId"
                  placeholder="请选择领用人"
                  clearable
                  @change="(e) => changePerson(e, '领用人')"
                >
                  <el-option
                    v-for="item in personList"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ formData.receivePersonName }}</span>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="是否审核" prop="isAudit">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.isAudit"
                  clearable
                  placeholder="请选择是否审核"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList('YesNo')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName("YesNo", formData.isAudit)
                }}</span>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">器具列表</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增</el-button
          >
        </div>

        <div class="formTable2">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column label="器具名称" props="assetId" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.assetId'"
                  :rules="rules.sonassetName"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    disabled
                    v-model="row.assetName"
                    placeholder="请选择器具名称"
                  />
                  <span v-else>{{ row.assetName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="企业编号" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.assetCode'"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    disabled
                    v-model="row.assetCode"
                    clearable
                    placeholder="请输入"
                  />
                  <span v-else>{{ row.assetCode }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="使用部门"
              props="usingDepartmentId"
              min-width="200"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.usingDepartmentId'"
                  label-width="0"
                  :rules="rules.sonusingDepartmentId"
                >
                  <SelectOriganizationDangerGrant
                    v-if="!props.isReadonly"
                    @change="(ids:string) => getSelectIds(ids, '使用部门',$index)"
                    @change-data="
                      (datas) => getSelectDatas(datas, '使用部门', $index)
                    "
                    :isCheckStrictly="true"
                    :isMultiple="false"
                    :disabled="false"
                    :data="dataObject('使用部门', $index)"
                    :selectData="row.usingDepartmentId"
                  />

                  <span v-else>{{ row.usingDepartmentName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="使用人"
              props="usingPersonName"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.usingPersonName'"
                  :rules="rules.sonusingPersonName"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.usingPersonName"
                    placeholder="请输入使用人"
                    clearable
                  />
                  <span v-else>{{ row.usingPersonName }}</span>
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column
              label="放发后位置"
              props="locationAfterGrantId"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.locationAfterGrantId'"
                  :rules="rules.sonlocationAfterGrantId"
                  label-width="0"
                >
                  <el-tree-select
                    v-if="!props.isReadonly"
                    placeholder="请输入位置"
                    style="width: 300px"
                    filterable
                    v-model="row.locationAfterGrantId"
                    :data="locationInfoTree"
                    node-key="id"
                    clearable
                    :props="{ label: 'locationName', children: 'nodes' }"
                    @node-click="(e:object) => handleLocationChange(e, $index)"
                    check-strictly
                    :render-after-expand="false"
                  />
                  <span v-else>{{ row.locationAfterGrant }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="80"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增器具列表信息 -->
    <eamgrantrecord-select
      :visible="selectDialog.visible"
      :breakList="breakList"
      @change-visible="changeVisible"
    />
    <!-- 选择原始凭证号 -->
    <use-apply-list-select-dialog
      :visible="applySelectDialog.visible"
      @change-visible="applyChangeVisible"
    />
    <!-- 查看领用申请详情 -->
    <use-apply-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisibleDialog"
    />
    <!-- 查看换型领用申请详情 -->
    <use-apply-other-edit
      :visible="addChangeDialog.visible"
      :title="addChangeDialog.title"
      :data="addChangeDialog.data"
      :is-readonly="addChangeDialog.readvisible"
      @change-visible="changeVisibleDialog"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { getUserInfo } from "@/api/user";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";

defineOptions({
  name: "EAMEAMGRANTRECORDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal == true && formData.id == "") {
      getUser();
      formData.grantDate = formData.grantDate
        ? formData.grantDate
        : dayjs(new Date()).format("YYYY-MM-DD");
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  version: "",
  recordCode: "",
  originalVoucherNo: "",
  assetKind: "",
  grantReason: "",
  grantDate: "",
  grantPersonId: "",
  grantPersonName: "",
  receiveDepartmentId: "",
  receiveDepartmentName: "",
  receivePersonId: "",
  receivePersonName: "",
  isAudit: "",
  remarks: "",
  deleted: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  grantPersonType: null,
  details: [
    // {
    //   id: "",
    //   version: "",
    //   recordId: "",
    //   seq: "",
    //   assetId: "",
    //   assetCode: "",
    //   assetName: "",
    //   usingDepartmentId: "",
    //   usingDepartmentName: "",
    //   usingPersonId: "",
    //   usingPersonName: "",
    //   locationBeforeGrantId: "",
    //   locationBeforeGrant: "",
    //   locationAfterGrantId: "",
    //   locationAfterGrant: "",
    //   isRepay: "",
    //   returnReason: "",
    //   repayDate: "",
    //   repayPersonId: "",
    //   repayPersonName: "",
    //   locationAfterRepayId: "",
    //   locationAfterRepay: "",
    //   remarks: "",
    //   deleted: "",
    //   organizationId: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    // },
  ],
});
const assetRepeatCheck = (rule: any, value: any, callback: any) => {
  if (value) {
    const details = formData.details;
    var findCnt = 0;
    for (let i = 0; i < details.length; i++) {
      const element = details[i];
      if (element.assetId === value) {
        findCnt++;
      }
    }
    if (findCnt > 1) {
      return callback(new Error("此器具已录入"));
    } else {
      callback();
    }
  }
};
/** rules规则 */
const rules = reactive({
  recordCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  originalVoucherNo: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  grantReason: [{ required: true, message: "请输入放发原因", trigger: "blur" }],
  grantDate: [{ required: true, message: "请选择发放日期", trigger: "change" }],
  grantPersonName: [
    { required: true, message: "请输入放发人", trigger: "blur" },
  ],
  grantPersonType: [
    { required: true, message: "请选择发放类型", trigger: "change" },
  ],
  receiveDepartmentId: [
    { required: true, message: "请选择领用部门", trigger: "change" },
  ],
  receivePersonId: [
    { required: true, message: "请选择领用人", trigger: "change" },
  ],
  isAudit: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonassetId: [
    { required: true, message: "请选择器具", trigger: "blur" },
    { validator: assetRepeatCheck, trigger: "blur" },
  ],
  sonassetName: [
    { required: true, message: "请选择器具名称", trigger: "blur" },
  ],
  sonusingDepartmentId: [
    { required: true, message: "请选择使用部门", trigger: "change" },
  ],
  sonusingPersonName: [
    { required: true, message: "请输入使用人", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonlocationBeforeGrant: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonlocationAfterGrantId: [
    { required: true, message: "请选择放发后位置", trigger: "change" },
  ],
  sonisRepay: [],
  sonreturnReason: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonrepayDate: [],
  sonrepayPersonName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonlocationAfterRepay: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  recordId: "",
  seq: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  usingDepartmentId: "",
  usingDepartmentName: "",
  usingPersonId: "",
  usingPersonName: "",
  locationBeforeGrantId: "",
  locationBeforeGrant: "",
  locationAfterGrantId: "",
  locationAfterGrant: "",
  isRepay: "",
  returnReason: "",
  repayDate: "",
  repayPersonId: "",
  repayPersonName: "",
  locationAfterRepayId: "",
  locationAfterRepay: "",
  remarks: "",
  deleted: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  selectDialog.value.visible = true;
  if (formData.details.length > 0) {
    getBreakList();
  }
  // let sondata = JSON.parse(JSON.stringify(details));
  // formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);

      formData.grantPersonType = String(formData.grantPersonType);
      changeDept(formData.receiveDepartmentId, "领用部门");

      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.recordCode = "";
  formData.originalVoucherNo = "";
  formData.assetKind = "";
  formData.grantReason = "";
  formData.grantDate = "";
  formData.grantPersonId = "";
  formData.grantPersonName = "";
  formData.receiveDepartmentId = "";
  formData.receiveDepartmentName = "";
  formData.receivePersonId = "";
  formData.receivePersonName = "";
  formData.isAudit = "";
  formData.remarks = "";
  formData.deleted = "";
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.grantPersonType = null;
  // formData.details = [JSON.parse(JSON.stringify(details))];
  formData.details = [];
  personList.value = [];
  personList1.value = [];
  breakList.value = [];
}

const loading = ref(false);

/** 发放记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (formData.details.length == 0) {
        ElMessage.error("请添加至少一项器具");
        return;
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/mtgrantrecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/mtgrantrecord/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  // 编辑获取详情时进行赋值
  breakList.value = [];
  formData.details.forEach((item) => {
    if (item.assetId) {
      breakList.value.push({
        id: item.assetId,
        assetCode: item.assetCode,
        assetName: item.assetName,
        locationId: item.locationBeforeGrantId,
        locationName: item.locationBeforeGrant,
      });
    }
  });
}

// 获取当前用户信息
const getUser = async () => {
  const res = await getUserInfo();
  formData.grantPersonId = res.data.userId;
  formData.grantPersonName = res.data.userName;
};
/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string, index: number) {
  if (item == "领用部门") {
    formData.receivePersonId = "";
    formData.receivePersonName = "";
    formData.receiveDepartmentId = ids;
    personList.value = [];
    changeDept(ids, item);
  } else if (item == "使用部门" && index != null) {
    formData.details[index].usingDepartmentId = ids;
  }
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, item: any, index: number) {
  if (item == "领用部门") {
    formData.receiveDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  } else if (item == "使用部门" && index != null) {
    formData.details[index].usingDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
}

const dataObject = (item: string, index: number) => {
  return {
    name: item == "领用部门" ? "领用部门" : "使用部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const changeDept = async (id, name) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });
    if (name == "领用部门") {
      personList.value = res.data;
      personList.value.map((item: any) => {
        item.label = `${item.firstName}`;
        item.value = `${item.id}`;
      });
    }
  }
};

// 人员改变时
const changePerson = (e: any, name: string) => {
  if (e) {
    if (name == "领用人") {
      personList.value.forEach((item: any) => {
        if (item.id == e) {
          formData.receivePersonName = item.firstName;
        }
      });
    }
  } else {
    formData.receivePersonId = "";
    formData.receivePersonName = "";
  }
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
// 点击位置树
const handleLocationChange = (e: object, index: number) => {
  formData.details[index].locationAfterGrantId = e.id;
  formData.details[index].locationAfterGrant = e.locationName;
};

// 点击器具
const tableIndex = ref(0);
function openSelectDialog(row: any, index: number) {
  tableIndex.value = index;
  changeVisible(true, null);
}
//器具显隐
const selectDialog = ref({
  visible: false,
});
// const changeVisible = (val: boolean, data: any) => {
//   if (data) {
//     formData.details[tableIndex.value].assetId = data.id;
//     formData.details[tableIndex.value].assetCode = data.assetCode;
//     formData.details[tableIndex.value].assetName = data.assetName;
//     formData.details[tableIndex.value].locationBeforeGrantId = data.locationId;
//     formData.details[tableIndex.value].locationBeforeGrant = data.locationName;
//   }
//   selectDialog.value.visible = val;
// };

const changeVisible = (val: boolean, data: any) => {
  if (data) {
    formData.details = [];
    data.forEach((item) => {
      formData.details.push({
        assetId: item.id,
        assetCode: item.assetCode,
        assetName: item.assetName,
        locationBeforeGrantId: item.locationId,
        locationBeforeGrant: item.locationName,
      });
    });
  }
  selectDialog.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const breakList = ref([]);
const getBreakList = () => {
  breakList.value = [];
  formData.details.forEach((item) => {
    if (item.assetId) {
      breakList.value.push({
        id: item.assetId,
        assetCode: item.assetCode,
        assetName: item.assetName,
        locationId: item.locationBeforeGrantId,
        locationName: item.locationBeforeGrant,
      });
    }
  });
};

// 领用弹窗显隐
const applySelectDialog = ref({
  visible: false,
});

function openApplySelectDialog() {
  applySelectDialog.value.visible = true;
}

const applyChangeVisible = (val: boolean, data: any) => {
  if (data) {
    formData.originalVoucherNo = data.recordCode || "";
  }
  applySelectDialog.value.visible = val;
};

onMounted(() => {
  getUser();
  getLocationInfoTree();
});

// 定义领用申请数据
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: true,
  title: "领用申请详情",
  data: {},
});

// 定义换型领用申请数据
const addChangeDialog = reactive<DialogOption>({
  visible: false,
  readvisible: true,
  title: "换型领用申请详情",
  data: {},
});

/** 打开器具领用申请表单弹窗 详情 */
async function getInfo() {
  if (!formData.originalVoucherNo) {
    ElMessage.error("原始凭证号不能为空");
  }
  request({
    url: `/eam/eammtuseapply/code/get/${formData.originalVoucherNo}`,
    method: "get",
  })
    .then((data) => {
      if (data.data.applyType === 1) {
        addDialog.data = data.data;
        addDialog.visible = true;
      } else if (data.data.applyType === 2) {
        addChangeDialog.data = data.data;
        addChangeDialog.visible = true;
      }
    })
    .catch((res) => {
      ElMessage.error("当前原始凭证号查询不到对应领用申请");
      console.log(res);
    });
}

function changeVisibleDialog(value: boolean) {
  addDialog.visible = value;
  addChangeDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    addChangeDialog.data = {};
  }
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable2 {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable2 .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable2 .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable2 .el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(
    .el-dialog .search-container .el-form-item--default .el-form-item__label
  ) {
  // 固定宽度
  justify-content: end;
}
</style>
